package com.muyu.cloud.common.many.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.autoconfigure.MybatisPlusAutoConfiguration;
import com.muyu.cloud.common.many.datasource.constents.DatasourceContent;
import com.muyu.cloud.common.many.datasource.domain.model.DataSourceInfo;
import com.muyu.cloud.common.many.datasource.factory.DruidDataSourceFactory;
import com.muyu.cloud.common.many.datasource.role.DynamicDataSource;
import com.muyu.cloud.common.saas.domain.model.EntInfo;
import com.muyu.cloud.common.saas.exception.SaaSException;
import com.muyu.common.core.domain.Result;
import com.muyu.common.core.utils.SpringUtils;
import com.muyu.common.system.domain.Datasource;
import com.muyu.common.system.domain.SysUser;
import com.muyu.common.system.remote.RemoteSaaSService;
import com.muyu.common.system.remote.RemoteUserService;
import lombok.extern.log4j.Log4j2;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: DongZeLiang
 * @date: 2024/6/3
 * @Description: 多数据源
 * @Version: 1.0
 */
@Log4j2
@Component
@AutoConfiguration(before = {MybatisPlusAutoConfiguration.class, MybatisAutoConfiguration.class})
public class ManyDataSource implements ApplicationRunner{
    private List<EntInfo> dataSourceInfoList(){
        RemoteSaaSService remoteSaaSService = SpringUtils.getBean(RemoteSaaSService.class);
Result<List<Datasource>> tableDataInfoResult = remoteSaaSService.findDatabaseList();
        if (tableDataInfoResult==null){
            throw new SaaSException("saas远调数据源错误");
        }
        List<Datasource> data = tableDataInfoResult.getData();
        if (tableDataInfoResult.getCode() ==Result.SUCCESS && data !=null){
            List<EntInfo> list = new ArrayList<>();
            for (Datasource row : data) {
                list.add(
                        EntInfo.builder()
                                .entCode(row.getDatabaseName())
                                .ip(DatasourceContent.IP)
                                .port(DatasourceContent.PORT)
                                .build()
                );
            }
            return list;
        }else {
            log.error("远调数据源错误,远调数据为：{}", JSON.toJSONString(data));
            return null;
        }
    }

//    private List<EntInfo> dataPrimarySourceInfoList(){
//        List<EntInfo> list = new ArrayList<>();
//        list.add(
//                EntInfo.builder()
//                        .entCode()
//                        .ip(DatasourceContent.IP)
//                        .port(DatasourceContent.PORT)
//                        .build()
//        );
//        return list;
//    }

    @Bean
    public DynamicDataSource dynamicDataSource(DruidDataSourceFactory druidDataSourceFactory) {
        // 企业列表 企业CODE，端口，IP
        Map<Object, Object> dataSourceMap = new HashMap<>();
        dataSourceInfoList()
                .stream()
                .map(entInfo -> DataSourceInfo.hostAndPortBuild(entInfo.getEntCode(), entInfo.getIp(), entInfo.getPort()))
                .forEach(dataSourceInfo -> {
                    dataSourceMap.put(dataSourceInfo.getKey(), druidDataSourceFactory.create(dataSourceInfo));
                });
        //设置动态数据源
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
//        dynamicDataSource.setDefaultTargetDataSource(masterDataSource());
        dynamicDataSource.setTargetDataSources(dataSourceMap);
        //将数据源信息备份在defineTargetDataSources中
        dynamicDataSource.setDefineTargetDataSources(dataSourceMap);
        return dynamicDataSource;
    }

    @Override
    public void run(ApplicationArguments args) {
        DruidDataSourceFactory druidDataSourceFactory = SpringUtils.getBean(DruidDataSourceFactory.class);
        DynamicDataSource dynamicDataSource = SpringUtils.getBean(DynamicDataSource.class);
        for (EntInfo entInfo : dataSourceInfoList()) {
            DataSourceInfo dataSourceInfo = DataSourceInfo.hostAndPortBuild(
                    entInfo.getEntCode(), entInfo.getIp(), entInfo.getPort()
            );
            DruidDataSource druidDataSource = druidDataSourceFactory.create(dataSourceInfo);
            dynamicDataSource.put(dataSourceInfo.getKey(), druidDataSource);
            log.info("存储数据连接池为：key:{}",dataSourceInfo.getKey());
        }
    }
}
